package com.ktg.mes.jimureport.service;

import com.ktg.common.constant.Constants;
import com.ktg.common.core.domain.model.LoginUser;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.framework.web.service.TokenService;
import com.ktg.mes.util.TokenUtils;
import io.jsonwebtoken.Claims;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class JimuReportTokenService implements JmReportTokenServiceI  {

    @Autowired
    TokenService tokenService;

    @Override
    public String getUsername(String token) {
        LoginUser loginUser = tokenService.getLoginUser(token);
        return loginUser.getUsername();
    }

    @Override
    public Boolean verifyToken(String token) {
        // 校验token
        LoginUser loginUser = tokenService.getLoginUser(token);
        if(StringUtils.isNotNull(loginUser)){
            // 刷新token有效期
            // tokenService.refreshToken(loginUser);
            // 超级管理员不需要鉴权
            if(loginUser.getUser() != null && loginUser.getUser().isAdmin()){
                return true;
            }else{
                // //校验菜单权限
                // Set<String> permissions = loginUser.getPermissions();
                // if(permissions != null && permissions.contains("report:jimu:list"))
                //     return true;
            }
            tokenService.verifyToken(loginUser);
            return true;
        }
        return false;
    }

    @Override
    public String getToken(HttpServletRequest request) {
        return TokenUtils.getTokenByRequest(request);
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        HashMap<String, Object> map = new HashMap<>();
        LoginUser loginUser = tokenService.getLoginUser(token);
        //设置用户名称
        map.put("SYS_USER_CODE",loginUser.getUsername());
        //设置部门id
        map.put("SYS_DEPT_ID",loginUser.getDeptId());
        return map;
    }

    @Override
    public HttpHeaders customApiHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("token",getToken());
        headers.add("X-Access-Token",getToken());
        return headers;
    }
}
